<?php
namespace Home\ORG;
//curl调用微信api地址返回数据类
class WeixinThirdSDK {
	private $third_appid;
	private $third_appsecret;
	private $third_access_token;
	//初始化appid 和 secret
	public function __construct($tappid,$tsecret){ 
		$this->third_appid = $tappid;
		$this->third_appsecret = $tsecret;
		$token = S('third_access_token');
		if( !empty($token) ){
			$this->third_access_token = $token;
		}else{
			$this->third_token();
			
		}
		//file_put_contents($_SERVER['DOCUMENT_ROOT'].'/Uploads/1.txt', $token);
	}

	//下载多媒体文件
	function downloadMedia($appid,$serverId,$tryCount=1,$access_token=false){
		if(!$access_token){
			$access_token=S('access_token'.$appid);
		}
		if(!$access_token){
			//TODO 如果当access_token超时后，可以使用refresh_token进行刷新，refresh_token拥有较长的有效期（30天），当refresh_token失效的后，需要用户重新授权。
			throw new \Exception('access_token已过期，请用户重新网页授权或refresh token', -96);
		}
		$url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$access_token."&media_id=".$serverId;
		$ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);    
        curl_setopt($ch, CURLOPT_NOBODY, 0);    //对body进行输出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $package = curl_exec($ch);
        $httpinfo = curl_getinfo($ch);
       
        curl_close($ch);
        $media = array_merge(array('mediaBody' => $package), $httpinfo);
        
        //求出文件格式
        preg_match('/\w\/(\w+)/i', $media["content_type"], $extmatches);
        $fileExt = $extmatches[1];
        //如果token失效，则重新获取一次token
        if(($fileExt=='json')&&($tryCount==1)){
        	$errArr=json_decode($media['mediaBody'],true);
        	if(in_array($errArr['errcode'], array(40001,40014,42001))){
        		$requestTokenRe=$this->token_now();
        		if($requestTokenRe===true){
	        		return $this->downloadMedia($serverId,2);
	        	}
	        	return array('fileExt'=>$fileExt,'mediaBody'=>json_encode($requestTokenRe));
        	}
        }
        $media['fileExt']=$fileExt;
        return $media;
	
	}

	//获取第三方平台component_access_token
	private function third_token(){
		// $m=D('Home/ComponentVerifyTicket');
		$m=new \Home\Model\ComponentVerifyTicketModel();
		$component_verify_ticket=$m->getLatest();
		$url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';
		$postDatas=array('component_appid'=>$this->third_appid,'component_appsecret'=>$this->third_appsecret,'component_verify_ticket'=>$component_verify_ticket,);
		$gettoken = $this->https_request($url,json_encode($postDatas));
		if ( isset($gettoken['errcode']) ) {
			// $this->third_access_token = $gettoken['errmsg'];
			throw new \Exception($gettoken['errmsg'],$gettoken['errcode']);		
		}
		else if( isset($gettoken['component_access_token']) ){
			S('third_access_token',$gettoken['component_access_token'],$gettoken['expires_in']-3600);
			$this->third_access_token = $gettoken['component_access_token'];
		}
	}

	//获取预授权码pre_auth_code
	public function pre_auth_code(){
		//预授权码一旦使用不能再用，所以这里不能缓存
		// $pre_auth_code = S('pre_auth_code');
		// if($pre_auth_code){
		// 	return $pre_auth_code;
		// }
		$url = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=".$this->third_access_token;
		$postDatas=array();
		$postDatas['component_appid'] = $this->third_appid;
		$pre_auth_code = $this->https_request($url,json_encode($postDatas));
		if(array_key_exists('errcode', $pre_auth_code)){
			throw new \Exception($pre_auth_code['errmsg'], $pre_auth_code['errcode']);
		}
		// S('pre_auth_code',$pre_auth_code['pre_auth_code'],$pre_auth_code['expires_in']-60);
		return $pre_auth_code['pre_auth_code'];
	}

	//根据获取预授权码获取公众号的接口调用凭据和授权信息
	public function getPingju($auth_code){
		$url = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=".$this->third_access_token;
		$postDatas=array();
		$postDatas['component_appid'] = $this->third_appid;
		$postDatas['authorization_code'] = $auth_code;
		$allPingju = $this->https_request($url,json_encode($postDatas));
		// if(array_key_exists('errcode', $allPingju)){
		// 	throw new \Exception($allPingju['errmsg'], $allPingju['errcode']);
		// }
		return $allPingju;
	}

	//获取（刷新）授权公众号的接口调用凭据（令牌）
	public function getRefreshPingju($authorizer_appid,$authorizer_refresh_token){
		$url = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=".$this->third_access_token;
		$postDatas=array();
		$postDatas['component_appid'] = $this->third_appid;
		$postDatas['authorizer_appid'] = $authorizer_appid;
		$postDatas['authorizer_refresh_token'] = $authorizer_refresh_token;
		$allPingju = $this->https_request($url,json_encode($postDatas));
		if(array_key_exists('errcode', $allPingju)){
			throw new \Exception($allPingju['errmsg'], $allPingju['errcode']);
		}
		return $allPingju;
	}

	//获得代公众号发起网页授权的url并返回
	public function shouquan($appid,$url,$scope,$state){
	    //服务方的appid
	    $component_appid = $this->third_appid;
	    $url=urlencode($url);
	    $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$url."&response_type=code&scope=".$scope."&state=".$state."&component_appid=".$component_appid."#wechat_redirect";
		return $url;
	}

	//授权成功之后通过code换取待运维公众号的access_token
	public function getAccessToken($code,$appid){
	  	$url="https://api.weixin.qq.com/sns/oauth2/component/access_token?appid=".$appid."&code=".$code."&grant_type=authorization_code&component_appid=".$this->third_appid."&component_access_token=".$this->third_access_token;
	  	$txt = $this->https_request($url);
	  	if(array_key_exists('errcode', $txt)){
			throw new \Exception($txt['errmsg'], $txt['errcode']);
		}
		S('access_token'.$appid,$txt['access_token'],$txt['expires_in']-3600);
		return $txt;
	}

	//获取指定openid的用户的基本信息
	function thirdUserInfo($appid,$openid,$access_token=false) {
		if(!$access_token){
			$access_token=S('access_token'.$appid);
		}
		if(!$access_token){
			//TODO 如果当access_token超时后，可以使用refresh_token进行刷新，refresh_token拥有较长的有效期（30天），当refresh_token失效的后，需要用户重新授权。
			throw new \Exception('access_token已过期，请用户重新网页授权或refresh token', -96);
		}
		$url = "https://api.weixin.qq.com/sns/userinfo?lang=zh_CN&access_token=".$access_token."&openid=".$openid;
		$txt = $this->curl_get($url);
		if(array_key_exists('errcode', $txt)){
			throw new \Exception($txt['errmsg'], $txt['errcode']);
		}
		return $txt;
	}

	/**
    * 获取三方平台的jsapi_ticket
    */
   	function getThirdJs_ticket($authorizeToken) {
   		$ckey='Third_JS_TICKET'.md5($authorizeToken);
       if(S($ckey)){
           return S($ckey);
       }
       $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$authorizeToken."&type=jsapi";
       $txt = $this->https_request($url);
       if($txt['errcode']!=0){
           throw new \Exception($txt['errmsg'], $txt['errcode']);
       }else{
           S($ckey,$txt['ticket'], $txt['expires_in']-1200);
           return $txt['ticket'];
       }
   }
   //随机字符串
   function createNonceStr($length = 16) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
      $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
  }

  //发送模板消息
  function moban($appid,$datas,$access_token=false){
  	if(!$access_token){
		$access_token=S('access_token'.$appid);
	}
	if(!$access_token){
		//TODO 如果当access_token超时后，可以使用refresh_token进行刷新，refresh_token拥有较长的有效期（30天），当refresh_token失效的后，需要用户重新授权。
		throw new \Exception('access_token未获取发送失败', -96);
	}
  	$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
  	$res = $this->https_request($url,$datas);
  	return $res;
  }

















	//更新token
	private function token() {
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret;
		$txt = $this->https_request($url);
		return $txt;
	}
	
	//不带post的curl
	private function curl_get($url) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		$txt = curl_exec($ch);
		if($txt===false){
//			echo "cURL Error: " . curl_error($ch);
                    ob_start();
                    echo $url;
                    $info = curl_getinfo($ch);
                    var_dump($info);
                    $a = ob_get_contents();
                    file_put_contents('./test/1.txt', $a.curl_error($ch));
                    ob_clean();
		}
		//$info = curl_getinfo($ch);
		curl_close($ch);
		$txt = json_decode($txt,true);
		// if( isset($txt['errcode']) ){
		// 	//token过期重新获取token
		// 	if( $txt['errcode']==42001 ){
		// 		$this->token_now();
		// 	}
		// }
		// 		dump($txt);dump($info);die;
		return $txt;
	}
	
	private function curl_post($url, $body) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
		$txt = curl_exec($ch);
		if($txt===false){
//			echo "cURL Error: " . curl_error($ch);
//			$info = curl_getinfo($ch);
//			dump($info);
		}
		// 		$info = curl_getinfo($ch);
		curl_close($ch);
		$txt = json_decode($txt,true);
		// if( isset($txt['errcode']) ){
		// 	//token过期重新获取token
		// 	if( $txt['errcode']==42001 ){
		// 		$this->token_now();
		// 	}
		// }
		return $txt;
	}
	
	/**
	 * curl https 请求（支持 GET 和 POST）
	 * @param $url string
	 */
	private function https_request( $url, $data=NULL ) {
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		if (!empty($data)){
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($curl);
		#add
		//if($output===false){
		if ( curl_errno($curl) ) {
// 			echo "cURL Error: " . curl_error($curl);
			$info = curl_getinfo($curl);
// 			dump($info);
		}
		#add
		curl_close($curl);
		#add
		$output = json_decode($output, true);
		// if( isset($output['errcode']) ){
		// 	//token过期重新获取token
		// 	if( $output['errcode']==42001 ){
		// 		$this->token_now();
		// 	}
		// }
		#add
		return $output;
	}
	
	//curl下载图片
	public function curl_down_pic($url){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$txt = curl_exec($ch);
		if($txt===false){
//			echo "cURL Error: " . curl_error($ch);
//			$info = curl_getinfo($ch);
//			dump($info);
		}
		$info = curl_getinfo($ch);
		curl_close($ch);
		return array('txt'=>$txt,'info'=>$info);
	}
	
	//马上更新token并缓存
// 	public function token_now() {
// 		$gettoken = $this->token();
// 		if ( isset($gettoken['errcode']) ) {
// // 			$this->access_token = $gettoken['errmsg'];
// 			return $gettoken['errmsg'];
// 		}
// 		if( isset($gettoken['access_token']) ){
// 			S('token',$gettoken['access_token'],7000);
// 			$this->access_token = $gettoken['access_token'];
// 			return true;
// 		}
// 	}
	
	function menuCreate($strPost) {
		$url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$this->access_token;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $strPost);
		$txt = curl_exec($ch);
		$info = curl_getinfo($ch);
		curl_close($ch);
		return $txt;
	}
	//自定义菜单删除接口
	function deleteMenu() {
		$url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=".$this->access_token;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		$txt = curl_exec($ch);
		$info = curl_getinfo($ch);
		curl_close($ch);
		$txt = json_decode($txt,true);
		return $txt;
	}
	
	//获取关注着列表
	function userGet() {
		$url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$this->access_token;
		$txt = $this->https_request($url);
		return $txt;
	}
	
	//获取指定openid的用户的基本信息
	function userInfo($openid) {
		$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$this->access_token."&openid=".$openid;
		$txt = $this->curl_get($url);
		return $txt;
	}
	
	//给指定openid的用户发送消息
	function sendMessage($body,$appid,$access_token=false) {
		if(!$access_token){
			
		$access_token=S('access_token'.$appid);
	}
	if(!$access_token){
		//TODO 如果当access_token超时后，可以使用refresh_token进行刷新，refresh_token拥有较长的有效期（30天），当refresh_token失效的后，需要用户重新授权。
		throw new \Exception('access_token未获取发送失败', -96);
	}
		$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
		$txt = $this->curl_post($url, $body);
		return $txt;
	}
	
	//创建分组
	function createGroups($body) {
		$url = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token=".$this->access_token;
		$txt = $this->curl_post($url, $body);
		return $txt;
	}
	
	//修改分组名
	function updateGroups($body) {
		$url = "https://api.weixin.qq.com/cgi-bin/groups/update?access_token=".$this->access_token;
		$txt = $this->curl_post($url, $body);
		return $txt;
	}
	
	//查询所有分组
	function getGroups() {
		$url = "https://api.weixin.qq.com/cgi-bin/groups/get?access_token=".$this->access_token;
		$txt = $this->curl_get($url);
		return $txt;
	}
	
	//查询用户所在分组
	function getidGroups($body) {
		$url = "https://api.weixin.qq.com/cgi-bin/groups/getid?access_token=".$this->access_token;
		$txt = $this->curl_post($url, $body);
		return $txt;
	}
	
	//移动用户分组
	function updateMembersGroups($body) {
		$url = "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=".$this->access_token;
		$txt = $this->curl_post($url, $body);
		return $txt;
	}
	
	//上传多媒体文件
	function uploadMedia($data,$type){
		$url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=".$this->access_token."&type=".$type;
		$txt = $this->curl_post($url, $data);
		return $txt;
	
	}
	
	//生成二维码
	function createQrcode($body) {
		$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$this->access_token;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
		$txt = curl_exec($ch);
		$info = curl_getinfo($ch);
		curl_close($ch);
		return $txt;
	}
	
	//通过ticket换取二维码
	function showqrcode($ticket) {
		$url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$ticket;
// 		$ch = curl_init();
// 		curl_setopt($ch, CURLOPT_URL, $url);
// 		curl_setopt($ch, CURLOPT_HEADER, 0);
// 		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
// 		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
// 		$txt = curl_exec($ch);
// 		$info = curl_getinfo($ch);
// 		curl_close($ch);
// 		dump($txt);
// 		dump($info);die;
// 		$txt = json_decode($txt,true);
// 		return $txt;
		$hander = curl_init();
// 		$fp = fopen('Uploads/images.jpg','wb');
		curl_setopt($hander,CURLOPT_URL,$url);
// 		curl_setopt($hander, CURLOPT_PROXY, "http://192.168.0.140:3128");//使用代理
// 		curl_setopt($hander,CURLOPT_FILE,$fp);
		//curl_setopt($hander,CURLOPT_HEADER,0);
		//curl_setopt($hander,CURLOPT_FOLLOWLOCATION,1);
		curl_setopt($hander,CURLOPT_SSL_VERIFYHOST,0);//https
		curl_setopt($hander,CURLOPT_SSL_VERIFYPEER,0);//https
		curl_setopt($hander,CURLOPT_RETURNTRANSFER,true);//以数据流的方式返回数据,当为false是直接显示出来
		//curl_setopt($hander,CURLOPT_TIMEOUT,60);
		$result = curl_exec($hander);
		$info = curl_getinfo($hander);
// 		dump($info);
// 		dump($result);
		curl_close($hander);
// 		$fp = fopen('Uploads/images.jpg','w');
// 		fwrite($fp, $result);
// 		fclose($fp);die;
		
// 		dump($result);exit;
		//fclose($fp);
		Return $result;
	}
	
	
	//上传图文消息素材
	function uploadnews($body) {
		$url = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=".$this->access_token;
		$txt = $this->curl_post($url, $body);
		return $txt;
	}
	
	
	/**
	 * 使用code换取access_token
	 * @param $code
	 * @return json->array
	 */
	function oauth2Token($code) {
		//oauth2的方式获得openid
		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $this->appid . "&secret=" . $this->appsecret . "&code=" . $code . "&grant_type=authorization_code";
		$txt = $this->https_request($url);
		return $txt;
	}
	
	function oauth2Userinfo($token,$openid) {
		$url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $token . "&openid=" . $openid;
		$txt = $this->https_request($url);
		return $txt;
	}
	
        /**
        * 获取jsapi_ticket
        */
       // function getJs_ticket() {
       //     if(S('JS_TICKET')){
       //         return S('JS_TICKET');
       //     }
       //     $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$this->access_token."&type=jsapi";
       //     $txt = $this->https_request($url);
       //     if($txt['errcode'] == 0){
       //         S("JS_TICKET",$txt['ticket'], 7200);
       //         return $txt['ticket'];
       //     }else{
       //         return 0;
       //     }
       // }
	
	
	
	
	
	
	
	
	
}